const fs = require("fs");

const path = require("path");

const Table = require("cli-table");


class Utils {
    constructor () {
        // process.cwd() 是当前执行node命令时候的文件夹地址
        // 文件夹路径拼接
        this.folderPath = path.join(process.cwd(),"src");
        this.table = null;
    }

    getFile () {
         // 读取该文件夹
        let fileList = fs.readdirSync(this.folderPath);
        // console.log(fileList);

        fileList.forEach(item=>{
            // 文件路径拼接
            let filePath = path.join(this.folderPath,item);
            // 获取该文件的信息
            let fileData = fs.statSync(filePath);
            // console.log(fileData);
            this.table.push([
                item,
                fileData.size,
                fileData.ctime.toLocaleString(),
                fileData.mtime.toLocaleString()
            ])
        })
    }

    // 查看
    createTable () {
       
        this.table = new Table({
            head:["文件名","文件大小","文件创建时间","最后修改时间"],
            colWidths:[25,25,25,25]
        });
        this.getFile();
        console.log(this.table.toString())
    }

    // 新增
    addFile (fileName,fileContent) {
        fs.writeFileSync(path.join(this.folderPath,fileName),fileContent)
    }

    // 删除
    getfileList () {
        let fileList = fs.readdirSync(this.folderPath);
        return fileList
    }
    del (fileName) {
        if(fs.existsSync(path.join(this.folderPath,fileName))){
            fs.unlinkSync(path.join(this.folderPath,fileName))
        }else {
            console.log("文件不存在")
        }
    }

    // 修改
    editFileName(fileName,newFileName){
        let oldPath = path.join(this.folderPath,fileName);
        let newPath = path.join(this.folderPath,newFileName);
        fs.renameSync(oldPath,newPath);
    }

}

exports.utils = new Utils();